package t4tools.lepath.query.eval;

import java.util.List;

public class IndexPredicate implements Predicate{

	private Integer index;
	private Variable variable;
	
	public IndexPredicate(String index) {
		this.index = Integer.parseInt(index);
	}

	public IndexPredicate(Variable variable) {
		this.variable = variable;
	}

	@Override
	public Object apply(Context context) {
		if (variable != null) {
			index = Integer.parseInt(String.valueOf(variable.getValue(context)));
		}
		Object current = context.get(ContextKey.CURRENT_NODE);
		if (current instanceof List) {
			return ((List) current).get(index);
		}
		if (current.getClass().isArray()) {
			Object[] asArray = (Object[]) current;
			return asArray[index];
		}
		return null;
	}
}
